$(document).ready(function () {
    
    $(".logistics-menu-toggle").live("click", function () {
        if ($(".logistics-menu").width() == 0) {
            $(".logistics-menu").stop().animate({ width: "80%" }, 200);
            $(".logistics-menu-toggle-bg").css("width", "100%");
        } else {
            $(".logistics-menu").stop().animate({ width: 0 },200);
            $(".logistics-menu-toggle-bg").css("width", 0);
        }
    });

    $(".logistics-menu-toggle-bg").live("click", function () {
        $(".logistics-menu").stop().animate({ width: 0 }, 200);
        $(".logistics-menu-toggle-bg").css("width", 0);
    });

    if ($(".logistics-order").length) {
        if ($("#logistics-tracking-form").length) {
            $(".logistics-order-messages").insertAfter($("#logistics-tracking-form"));
            if ($("#TrackingNumber").val() != "") {
                submitPageRequest(null, $("#logistics-tracking-form"), $(".order-shipment-detail-content"));
            }
        }
        if ($(".logistics-order-content #order-init").length) {
            submitPageRequest(null, $(".logistics-order-content form"));
        }
        if ($("#order-list-form").length) {
            submitDataRequest($("#order-list-form"));
        }
        if ($("#shipment-list-form").length) {
            submitDataRequest($("#shipment-list-form"));
        }
        $(".logistics-order-content input[type=button], .logistics-order-content .address-select-item, .logistics-order-menu .order-new, .logistics-order-subtotal input.gift-card-action").live("click", function (e) {
            if ($(this).attr("data-action") == "submit") {
                if ($(this).closest(".finalize-order-button").length) {
                    $(".giftcard-wrapper").remove();
                }
                if ($(".order-shipment-detail").length) {
                    submitPageRequest($(this), $(this).closest("form"), $(".order-shipment-action-content"));
                } else {
                    submitPageRequest($(this), $(this).closest("form"));
                }
            } else if ($(this).attr("data-action") == "clearOrder") {
                submitPageRequest($(this));
            } else if ($(this).attr("data-action") == "giftCard") {
                submitGiftCardRequest($(this));
            }
            e.stopPropagation();
            e.preventDefault();
        });
        $(".logistics-order-content [data-action=select]").live("click", function () {
            $(".logistics-order-content [data-name=" + $(this).attr("data-name") + "]").removeClass("selected")
            $(this).addClass("selected");
            if ($(this).attr("data-name")) {
                $("#" + $(this).attr("data-name")).remove();
                $(this).closest("form").append("<input type='hidden' id='" + $(this).attr("data-name") + "' name='" + $(this).attr("data-name") + "' value='" + $(this).attr("data-value") + "' />");
            }
            if ($(this).attr("data-name2")) {
                $("#" + $(this).attr("data-name2")).remove();
                $(this).closest("form").append("<input type='hidden' id='" + $(this).attr("data-name2") + "' name='" + $(this).attr("data-name2") + "' value='" + $(this).attr("data-value2") + "' />");
            }
        });
        $(".logistics-order-steps li, #finalize-edit-form input[type=button]").live("click", function () {
            if (!$(".logistics-order-steps").hasClass("disabled") && !$(this).hasClass("Disabled") && $(this).attr("data-url")) {
                submitPageRequest($(this));
            }
        });
        $(".package-calculate").live("click", function () {
            costCalculate();
        });
        $(".package-tracking-action input").live("click", function (e) {
            slideAnimate($(this).closest(".order-shipment-detail"), $(".order-shipment-action"), "left");
            $(".logistics-order-messages").empty().insertBefore($(".logistics-order-content"));
            $(".order-shipment-action-content").empty();
            submitPageRequest($(this), null, $(".order-shipment-action-content"));
            e.preventDefault();
            return false;
        });
        $("#logistics-tracking-form input").live("keypress", function (e) {
            if (e.keyCode == 13) {
                validateTrackingForm($("#logistics-tracking-form"));
                e.preventDefault();
                return false;
            }
        });
        $("#logistics-tracking-form .tracking-button").live("click", function () {
            validateTrackingForm($("#logistics-tracking-form"));
        });

        $("#package-form input, #package-form select").live("change", function () {
            if (checkSubmitPackageForm()) {
                submitPageRequest(null, $(this).closest("form"), null, null, true);
            }
        });

        $(".payment-info .credit-card").live("click", function () {
            $(".payment-info .credit-card").removeClass("selected");
            $(this).addClass("selected");
            $(this).find(".card-select input").prop('checked', true);
        });

        // Address select
        $(".address-form .address-select").live("click", function () {
            slideAnimate($(".address-form"), $(".address-select-list"), "left");
        });
        $(".address-select-list .step-back").live("click", function () {
            slideAnimate($(".address-select-list"), $(".address-form"), "right");
        });
        $(".address-select-list .address-search-field").live("keypress keyup keydown blur", function () {
            var val = $(this).val().toLowerCase();
            if (val == "") {
                $(".address-select-list .address-select-item").removeClass("hide");
            } else {
                $(".address-select-list .address-select-item").each(function () {
                    var text = $(this).text().toLowerCase();
                    if (text.indexOf(val) > 0) {
                        $(this).removeClass("hide");
                    } else {
                        $(this).addClass("hide");
                    }
                });
            }
        });

        // My order details
        $(".order-list-row").live("click", function () {
            if ($(".hidden-data .order-list-shipments[data-id=" + $(this).attr("data-id") + "]").length) {
                $(".order-list-detail-content").empty();
                $(".hidden-data .order-list-shipments[data-id=" + $(this).attr("data-id") + "]").clone().appendTo($(".order-list-detail-content"));
                $(".order-list-detail .order-list-id").text($(this).attr("data-id"));
                slideAnimate($(".order-list-table"), $(".order-list-detail"), "left");
            }
        });
        $(".order-shipment-row").live("click", function (e) {
            if ($(e.target).hasClass("download-waybill")) {
                return;
            }
            if ($(this).attr("data-id") && $(this).attr("data-id") != 0) {
                $(".order-shipment-detail-content").empty();
                slideAnimate($(".order-list-detail"), $(".order-shipment-detail"), "left");
                submitPageRequest($(this), null, $(".order-shipment-detail-content"));
            }
        });
        $(".shipment-list-row").live("click", function (e) {
            if ($(e.target).hasClass("download-waybill")) {
                return;
            }
            if ($(this).attr("data-id") && $(this).attr("data-id") != 0) {
                $(".order-shipment-detail-content").empty();
                slideAnimate($(".order-list-table"), $(".order-shipment-detail"), "left");
                submitPageRequest($(this), null, $(".order-shipment-detail-content"));
            }
        });
        $(".order-list-detail .step-back").live("click", function () {
            slideAnimate($(".order-list-detail"), $(".order-list-table"), "right");
        });
        $(".order-shipment-detail .step-back").live("click", function () {
            if ($("#shipment-list-form").length) {
                slideAnimate($(".order-shipment-detail"), $(".order-list-table"), "right");
            } else {
                slideAnimate($(".order-shipment-detail"), $(".order-list-detail"), "right");
            }
        });
        $(".order-shipment-action .step-back").live("click", function () {
            slideAnimate($(".order-shipment-action"), $(".order-shipment-detail"), "right");
            $(".logistics-order-messages").empty().insertAfter($("#logistics-tracking-form"));
            if ($(".logistics-order-tracking form").length) {
                submitPageRequest(null, $(".logistics-order-tracking form"), $(".order-shipment-detail-content"));
                $(".order-shipment-detail-content").empty();
            } else if ($(".order-shipment-detail-content #shipment-id").length) {
                submitPageRequest($(".order-shipment-detail-content #shipment-id"), null, $(".order-shipment-detail-content"));
                $(".order-shipment-detail-content").empty();
            }
            
        });

        // Data request pager
        $(".pagination a").live("click", function (e) {
            if (!$(this).parent().hasClass("disabled")) {
                var page;
                switch ($(this).attr("data-page")) {
                    case "next":
                        $("#data-page").val(parseInt($("#data-page").val()) + 1);
                        break;

                    case "prev":
                        $("#data-page").val(parseInt($("#data-page").val()) - 1);
                        break;

                    default:
                        $("#data-page").val(parseInt($(this).attr("data-page")));
                }
                submitDataRequest($(this).closest("form"));
            }
            e.stopPropagation();
            return false;
        });
    }
});

function checkSubmitPackageForm() {
    if ($("[name=SpotshubPackageSize]:checked").length) {
        if (parseInt($("[name=SpotshubPackageSize]:checked").val()) != 0 ||
            (parseInt($("[name=SpotshubPackageSize]:checked").val()) == 0 && isPositiveNum($("#Length").val()) && isPositiveNum($("#Width").val()) && isPositiveNum($("#Height").val()) && isPositiveNum($("#Weight").val()))) {
            return true;
        }
    }
    return false;
}

function submitGiftCardRequest(elem) {
    var url = elem.attr("data-url");
    var datavalues = {};
    var code = $("#GiftCardCode").val();
    if (code != null) {
        datavalues = { giftCardCode: code };
    }
    if (url != "") {
        $(".logistics-giftcard-loading").show();
        if ($("#GiftCardCode").length) {
            $("#GiftCardCode").prop("disabled", true);
        }
        $(".giftcard-message").empty();
        $.ajax({
            url: url,
            type: "POST",
            dataType: "JSON",
            data: datavalues
        }).done(function (data) {
            if (data.html)
            {
                $(".logistics-order-subtotal").html(data.html);
            }
            if (data.message) {
                $(".giftcard-message").html(data.message);
            }
        }).always(function () {
            $(".giftcard-container").show();
            $(".logistics-giftcard-loading").hide();
            if ($("#GiftCardCode").length) {
                $("#GiftCardCode").prop("disabled", false);
            }
        });
    }
}

function submitDataRequest(form) {
    var url = form.attr("action");
    var type = "POST";
    var datavalues = form.serializeArray();
    form.find("tbody").empty();
    $(".logistics-order-loading").show();
    $.ajax({
        url: url,
        type: type,
        dataType: "JSON",
        data: datavalues
    }).done(function (data) {
        if (data.data) {
            form.find(".data tbody").html(data.data);
        }
        if (data.hiddendata) {
            form.find(".hidden-data").html(data.hiddendata);
        }
        if (data.pagerdata) {
            form.find(".pager").html(data.pagerdata);
        }
        $(".logistics-order-loading").hide();
    });
}

function submitPageRequest(elem, form, datawrapper, noclearmessage, modifypackage) {
    var url = "";
    var type = "POST";
    var datavalues = [];
    if (form != null) {
        url = form.attr("action");
        type = form.attr("method");
        datavalues = form.serializeArray();
    } else {
        url = elem.attr("data-url");
    }
    if (elem != null && elem.attr("data-name") != "" && elem.attr("data-value") != "") {
        datavalues.push({ name: elem.attr("data-name"), value: elem.attr("data-value") });
    }
    if (elem != null && elem.attr("data-name2") != "" && elem.attr("data-value2") != "") {
        datavalues.push({ name: elem.attr("data-name2"), value: elem.attr("data-value2") });
    }
    if (elem != null && elem.attr("data-packageid") != null && elem.attr("data-packageid") != "") {
        datavalues.push({ name: "requestpackageid", value: elem.attr("data-packageid") });
    }
    if (url != "" && type != "") {
        $(".logistics-order-steps").addClass("disabled");
        if (datawrapper == null && modifypackage == null) {
            $(".logistics-order-content").hide();
        }
        if (modifypackage == null) {
            $(".logistics-order-loading").show();
        } else {
            datavalues.push({ name: "packageAction", value: "modify" });
            $(".logistics-order-subtotal-loading").show();
            $(".logistics-order-subtotal").hide();
        }
        if (noclearmessage != true) {
            $(".logistics-order-messages").empty();
        }
        if ($("body").scrollTop() > $(".logistics-order-content-wrapper").offset().top) {
            $("html, body").stop().animate({
                scrollTop: $(".logistics-order-content-wrapper").offset().top
            }, 300);
        }
        $.ajax({
            url: url,
            type: type,
            dataType: "JSON",
            data: datavalues
        }).done(function (data) {
            if (data.redirect != null && data.redirect != "") {
                window.location.href = data.redirect;
            }
            else
            {
                if (data.html && modifypackage == null) {
                    if (datawrapper == null) {
                        $(".logistics-order-content").html(data.html).show();
                    } else {
                        datawrapper.html(data.html).show();
                    }
                }
                if (data.ordermenuhtml && data.ordermenuhtml != "") {
                    if (modifypackage == null) {
                        $(".logistics-order-steps").html(data.ordermenuhtml);
                        if ($(".logistics-order-menu").height() == 0) {
                            $(".logistics-order-menu").stop().animate({
                                height: $(".logistics-order-steps").height()
                            }, 200);
                        }
                    }
                } else {
                    if ($(".logistics-order-menu").height() > 0) {
                        $(".logistics-order-menu").stop().animate({
                            height: 0
                        }, 200);
                    }
                }
                if (data.sumhtml) {
                    $(".logistics-order-subtotal").html(data.sumhtml);
                    $(".logistics-order").addClass("has-sum");
                }
                if (data.messages != "" && typeof (data.messages) != "undefined" && noclearmessage != true) {
                    $(".logistics-order-messages").html("<div class='messages-wrapper'>" + data.messages + "</div>");
                }
                if (data.haspending) {
                    $(".shipping-pending-order").show();
                } else {
                    $(".shipping-pending-order").hide();
                }
                if (data.menuitem && data.menuitem != "") {
                    $(".logistics-menuitem").removeClass("active");
                    $(".logistics-menuitem." + data.menuitem).addClass("active");
                }
                if (data.shipmentchangesuccess == true) {
                    slideAnimate($(".order-shipment-action"), $(".order-shipment-detail"), "right");
                    $(".order-shipment-detail-content").empty();
                    if ($(".logistics-order-tracking form").length) {
                        submitPageRequest(null, $(".logistics-order-tracking form"), $(".order-shipment-detail-content"), true);
                    }
                }
                if ($("body").scrollTop() > $(".logistics-order-content-wrapper").offset().top) {
                    $("html, body").stop().animate({
                        scrollTop: $(".logistics-order-content-wrapper").offset().top
                    }, 300);
                }
            }
        }).error(function () {

        }).always(function () {
            $(".logistics-order-steps").removeClass("disabled");
            $(".logistics-order-loading").hide();
            $(".logistics-order-subtotal-loading").hide();
            $(".logistics-order-subtotal").show();
            if (datawrapper == null) {
                $(".logistics-order-content").show();
            }
        });
    }
}

function isPositiveNum(num) {
    if (num != "" && !isNaN(parseInt(num))) {
        if (parseInt(num) > 0) {
            return true;
        }
    }
    return false;
}

function slideAnimate(curslide, nextslide, direction) {
    var dest = 0;
    if (direction == "left") {
        dest = "-100%";
        nextslide.css({
            position: "absolute",
            left: "100%",
            top: 0,
            height: "auto"
        });
    } else if (direction == "right") {
        dest = "100%";
        nextslide.css({
            position: "absolute",
            left: "-100%",
            top: 0,
            height: "auto"
        });
    }
    curslide.stop().animate({
        left: dest
    }, 200);
    nextslide.stop().animate({
        left: 0
    }, 200, function () {
        curslide.css({position: "absolute", height: 0});
        nextslide.css("position", "relative");
    });
    if ($("body").scrollTop() > $(".logistics-order-content-wrapper").offset().top) {
        $("html, body").stop().animate({
            scrollTop: $(".logistics-order-content-wrapper").offset().top
        }, 300);
    }
}

function validateTrackingForm(form) {
    submitPageRequest(null, form, $(".order-shipment-detail-content"))
}

function costCalculate() {
    $(".package-estimate").html("");
    var calculateAjaxRequest = $.ajax({
        url: $(".package-calculate").attr("data-url"),
        type: "POST",
        data: $(".logistics-order-content form").serializeArray(),
        timeout: 15000
    }).done(function (response) {
        if (response.Cost > 0) {
            $(".package-estimate").html("$" + parseFloat(response.Cost).toFixed(2));
        } else {
            $(".package-estimate").html("N/A");
        }
        if (response.sumhtml) {
            $(".logistics-order-subtotal").html(response.sumhtml);
            $(".logistics-order").addClass("has-sum");
        }
    }).error(function () {
    }).always(function () {
    });
}